package com.mrzhou.log.publisher;

import com.mrzhou.core.tool.utils.Exceptions;
import com.mrzhou.core.tool.utils.Func;
import com.mrzhou.core.tool.utils.SpringUtil;
import com.mrzhou.log.constant.LogConstant;
import com.mrzhou.log.entity.LogError;
import com.mrzhou.log.event.ErrorLogEvent;
import com.mrzhou.web.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class ErrorLogPublisher {

    public static void publisherEvent(Throwable throwable, String requestUri) {
        LogError logError = new LogError();
        HttpServletRequest request = WebUtil.getRequest();
        logError.setRequestUri(requestUri);
        if(!Func.isEmpty(throwable)) {
            logError.setStackTrace(Exceptions.getStackTraceAsString(throwable));
            logError.setExceptionName(throwable.getClass().getName());
            logError.setMessage(throwable.getMessage());
            StackTraceElement[] elements = throwable.getStackTrace();
            if(Func.isNotEmpty(elements)) {
                StackTraceElement element = elements[0];
                logError.setMethodName(element.getMethodName());
                logError.setMethodClass(element.getClassName());
                logError.setFileName(element.getFileName());
                logError.setLineNumber(element.getLineNumber());
            }
            logError.setRemoteIp(WebUtil.getIp(request));
            logError.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER));
            logError.setRequestUri(WebUtil.getPath(request.getRequestURI()));
            logError.setMethod(request.getMethod());
            logError.setParameters(WebUtil.getRequestParamString(request));
            logError.setCreateBy(Func.toStr(WebUtil.getUserId()));
            Map<String, Object> map = new HashMap<>();
            map.put(LogConstant.EVENT_LOG, logError);
            SpringUtil.publishEvent(new ErrorLogEvent(map));
       }

    }

}
